package com.durian.base.frame.viewbinding

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import kotlin.reflect.KClass

class TitleBarViewBindingLazy<VM : ViewBinding> (
        private val viewBindingClass: KClass<VM>,
        private var viewGroup: ViewGroup? = null,
        private var attach : Boolean = false,
        private var inflater: ()-> LayoutInflater
) : Lazy<VM> {
    private var cached: VM? = null

    override val value: VM
        get() {
            val viewBinding = cached
            return if (viewBinding == null) {
                val method = viewBindingClass.java.getMethod("inflate",LayoutInflater::class.java,ViewGroup::class.java,Boolean::class.java)
                (method.invoke(null,inflater.invoke(),viewGroup,attach) as VM).also {
                    cached = it
                }
            } else {
                viewBinding
            }
        }

    override fun isInitialized() = cached != null
}